package com.tc.travel.submitter.executor;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tc.travel.submitter.pojo.VisaAddUpdateDto;
import com.tc.travel.submitter.service.SessionBo;
import com.tc.travel.submitter.service.VisaBo;
import com.tc.travel.util.Consts;

@Component
public class VisaAddUpdateExecutor {
	private static Logger log = Logger.getLogger(VisaAddUpdateExecutor.class);

	@Autowired
	private SessionBo sessionBo;

	@Autowired
	private VisaBo visaBo;

	@Autowired
	private VisaAdd visaAdd;

	public void execute() {
		try {
			log.info("VisaAddUpdateExecutor.execute....");

			VisaAddUpdateDto visaAddUpdateDto = visaBo.getVisaForAddUpdate();
			if (visaAddUpdateDto != null) {
				log.info("found visaAddUpdateDto--->" + visaAddUpdateDto);

				String cookie = sessionBo.getCookie();
				log.info("cookie:" + cookie);

				int visaState = Consts.VISA_STATE_PUSH_SUCC;
				String errorMsg = "";
				String destVisaId = "";

				// 失败马上就重做，最多3次
				for (int i = 0; i < 3; i++) {
					try {
						// // dest visa id为空则增加
						// if (StringUtil.isEmpty(visaSubmitDto.getDestVisaId())) {
						destVisaId = visaAdd.execute(visaAddUpdateDto, cookie);
						// } else {
						// // TODO update
						// }

						// 更新状态为成功
						visaState = Consts.VISA_STATE_PUSH_SUCC;
						errorMsg = "";

						log.info("add visa success; try time: " + i + "; visa_info_id=" + visaAddUpdateDto.getVisaInfoId());
						break;// 成功就跳出
					} catch (Throwable e) {
						visaState = Consts.VISA_STATE_PUSH_FAIL;
						errorMsg = e.getMessage();
						log.error("add visa error; try time: " + i + "; visa_info_id=" + visaAddUpdateDto.getVisaInfoId() + "; " + e.getMessage(), e);
					}
				}

				log.info("updateVisaState:");
				visaBo.updateVisaState(visaAddUpdateDto.getVisaInfoId(), null, visaState, destVisaId, errorMsg);
			} else {
				log.info("no visaAddUpdateDto foud to push...end");
			}
		} catch (Throwable e) {
			log.error("VisaAddUpdateExecutor error: " + e.getMessage(), e);
		}
	}
}
